package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisMessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    OrderService orderService;

    /*
     *使用map接收页面提交的数据
     * */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String, Object> map) {
        try {
            String telephone = String.valueOf(map.get("telephone"));
            String validateCodeUser = String.valueOf(map.get("validateCode"));
            String validateCodeInRedis = jedisPool.getResource().get(RedisMessageConst.SENDTYPE_ORDER + "-" + telephone);

            if (validateCodeInRedis != null && validateCodeInRedis.equals(validateCodeUser)) {
                //设置预约方式
                map.put("orderType", Order.ORDERTYPE_WEIXIN);
                //调用预约服务
                Result result = orderService.addOrder(map);
                //预约成功后,发送通知短信
                if (result.isFlag()) {
                    //发送通知短信(必须是企业才可以申请)
                }
                return result;
            } else {
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ORDER_FAIL);
        }
    }

    /*
    * 页面需要什么
    * 体检人姓名  体检套餐名称   体检日期  预约类型
    * */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map<String,Object> resultMap = orderService.findById(id);
            Date orderDate = (Date) resultMap.get("orderDate");
            String orderDateStr = new SimpleDateFormat("yyyy-MM-dd").format(orderDate);
            resultMap.put("orderDate",orderDateStr);
            return new Result(true,MessageConst.QUERY_ORDER_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_ORDER_FAIL);
        }
    }
}
